﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ITextSharpPDF
{
    public static class Common
    {
        public static void SetWaterMark(ref Document doc, string pdfFilePath, string imageFilePath, float waterMarkSize)
        {
            PdfReader reader = null;
            PdfStamper stamper = null;
            string newPDFFileName = "";

            try
            {
                reader = new PdfReader(pdfFilePath);

                string waterPDF = Path.GetDirectoryName(pdfFilePath);
                string fileWater = Path.GetFileName(pdfFilePath).Replace(".pdf", "") + "-Stamper.pdf";

                newPDFFileName = Path.Combine(waterPDF, fileWater);

                stamper = new PdfStamper(reader, new FileStream(newPDFFileName, FileMode.OpenOrCreate));

                Image img = Image.GetInstance(imageFilePath);

                float width = doc.PageSize.Width;
                float height = doc.PageSize.Height;

                //像素
                float percent = waterMarkSize / img.Width;
                img.ScaleAbsoluteWidth(waterMarkSize);//缩放图片指定宽度
                img.ScaleAbsoluteHeight(img.Height * percent);//等比例缩放高度
                img.SetAbsolutePosition((width - waterMarkSize) / 2, (height - img.Height * percent) / 2);//设置水印位置
                img.Rotation = 95;//旋转角度

                //指定颜色透明,如：白色
                img.Transparency = new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

                //设置透明度
                //create new graphics state and assign opacity
                PdfGState graphicsState = new PdfGState();
                graphicsState.FillOpacity = 0.2F; // (or whatever)
                                                  //set graphics state to pdfcontentbyte
                PdfContentByte contentByte;
                int j = 0;
                int n = reader.NumberOfPages;
                while (j < n)
                {
                    j++;
                    contentByte = stamper.GetOverContent(j);
                    contentByte.SetGState(graphicsState);//设置透明度
                    contentByte.AddImage(img);
                }
            }
            finally
            {
                if (stamper != null) stamper.Close();
                if (stamper != null) reader.Close();

                //改名
                if (File.Exists(newPDFFileName))
                {
                    File.Delete(pdfFilePath);
                    FileInfo fi = new FileInfo(newPDFFileName);
                    fi.MoveTo(pdfFilePath);
                }
            }
        }
    }
}
